Public Partial Class FrmOrdenDePagoABM
    Inherits System.Web.UI.Page
    Public Proveedor As CapaDeNegocios.nProveedor = New CapaDeNegocios.nProveedor
    Public Factura As CapaDeNegocios.nFacturaCompra = New CapaDeNegocios.nFacturaCompra
    Public OrdenDePago As CapaDeNegocios.nOrdendePago = New CapaDeNegocios.nOrdendePago
    Public DetalleOrdenDePago As CapaDeNegocios.nDetalleOrdenDePago = New CapaDeNegocios.nDetalleOrdenDePago
    Public OpOtras As CapaDeNegocios.nOpOtras = New CapaDeNegocios.nOpOtras
    Public OpCuenta As CapaDeNegocios.nOpCuenta = New CapaDeNegocios.nOpCuenta
    Public OpCheque As CapaDeNegocios.nOpCheque = New CapaDeNegocios.nOpCheque
    Public Banco As CapaDeNegocios.nBanco = New CapaDeNegocios.nBanco
    Public Cuenta As CapaDeNegocios.nCuenta = New CapaDeNegocios.nCuenta
    Public Chequera As CapaDeNegocios.nChequera = New CapaDeNegocios.nChequera
    Public ChequeTercero As CapaDeNegocios.nChequesTerceros = New CapaDeNegocios.nChequesTerceros
    Public ChequesPropios As CapaDeNegocios.nChequesPropios = New CapaDeNegocios.nChequesPropios
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Session("Login") = "Anonimo" Then
            Response.Redirect("/")
        End If
        If Not Page.IsPostBack Then
            LimpiarCampos()
            LlenarCboProveedor()
            LLenarCboFacturas()
            BtnImprimir.Visible = False
            LnkOrdenes.OnClientClick = "javascript:var popup = window.open('FrmListadoOrdenDePago.aspx',(new Date().getTime()),'Width=700,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')"
            BtnImprimir.OnClientClick = "javascript:var popup = window.open('../Reportes/RptOrdenDePago.aspx',(new Date().getTime()),'Width=900,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')"
            LnkImputacion.OnClientClick = "javascript:var popup = window.open('FrmImputacionesCompras.aspx?Importe=" + LblTotal.Text + "',(new Date().getTime()),'Width=500,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')"

        End If
    End Sub
    Sub LimpiarCampos()
        LblFecha.Text = Now.Date.ToShortDateString()
        TxtObservacion.Text = ""
        LblTotal.Text = "0,00"
        LblError.Text = ""
        
    End Sub
    Sub LlenarCboProveedor()
        CboProveedor.Items.Clear()
        CboProveedor.DataSource = Proveedor.Listar("", "", "", "", "", "", "", "")
        CboProveedor.DataTextField = "RazonSocial"
        CboProveedor.DataValueField = "CodigoProv"
        CboProveedor.DataBind()
        If CboProveedor.Items.Count > 0 Then
            CboProveedor.SelectedIndex = 0
        End If
    End Sub
    Sub LLenarCboFacturas()
        CboFacturas.Items.Clear()
        CboFacturas.DataSource = Factura.ListarFacturas(0, CboProveedor.SelectedValue, "", "Pendiente", 0, 0, "", "")
        CboFacturas.DataTextField = "Numero"
        CboFacturas.DataValueField = "CodigoFactura"
        CboFacturas.DataBind()
        CboFacturas.Enabled = CboFacturas.Items.Count > 0
    End Sub

    Protected Sub CboProveedor_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CboProveedor.SelectedIndexChanged
        LLenarCboFacturas()
    End Sub

    Sub LlenarGrid(ByVal index As Integer)
        CboProveedor.Enabled = True
        LblTotal.Text = "0,00"
        If index <> -1 Then
            CboFacturas.Items(CboFacturas.SelectedIndex).Enabled = False
        End If
        Dim dts As DataSet = New DataSet()
        dts.Tables.Add("Tabla")
        dts.Tables(0).Columns.Add("Numero")
        dts.Tables(0).Columns.Add("CodigoFactura")
        dts.Tables(0).Columns.Add("Iva")
        dts.Tables(0).Columns.Add("Total")
        Dim Cont As Integer
        Cont = 0
        CboFacturas.Enabled = False
        For Cont = 0 To CboFacturas.Items.Count - 1
            If Not CboFacturas.Items(Cont).Enabled Then
                Dim dr As DataRow
                dr = dts.Tables(0).NewRow()
                dr("Numero") = CboFacturas.Items(Cont).Text
                dr("CodigoFactura") = CboFacturas.Items(Cont).Value.ToString()
                dr("IVA") = Factura.ListarFacturas(CboFacturas.Items(Cont).Value.ToString(), CboProveedor.SelectedValue, CboFacturas.Items(Cont).Text, "PENDIENTE", 0, 0, "", "").Tables(0).Rows(0)("IVA").ToString()
                dr("Total") = Factura.ListarFacturas(CboFacturas.Items(Cont).Value.ToString(), CboProveedor.SelectedValue, CboFacturas.Items(Cont).Text, "PENDIENTE", 0, 0, "", "").Tables(0).Rows(0)("Total").ToString()
                dts.Tables(0).Rows.Add(dr)
                LblTotal.Text = (CDbl(LblTotal.Text) + CDbl(dr("Total").ToString())).ToString()
            Else
                CboFacturas.Enabled = True
            End If
        Next
        GridFacturas.DataSource = dts
        GridFacturas.DataBind()


    End Sub

    Protected Sub LinkAgregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkAgregar.Click
        LlenarGrid(CboFacturas.SelectedIndex)
        LnkImputacion.OnClientClick = "javascript:var popup = window.open('FrmImputacionesCompras.aspx?Importe=" + LblTotal.Text + "',(new Date().getTime()),'Width=500,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')"
    End Sub

    Protected Sub GridFacturas_RowCommand(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridFacturas.RowCommand
        If e.CommandName = "Remover" Then
            CboFacturas.Items(CboFacturas.Items.IndexOf(CboFacturas.Items.FindByValue(CInt(e.CommandSource.Parent.Parent.FindControl("HFIdFactura").value.ToString())))).Enabled = True
            LlenarGrid(-1)
        End If
    End Sub

    Protected Sub GridFacturas_RowDataBound(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridFacturas.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim a As LinkButton = e.Row.FindControl("LnkMasInformacion")
            Dim b As HiddenField = e.Row.FindControl("HFIdFactura")
            a.OnClientClick = "javascript:var popup = window.open('FrmDetalleDeFacturaCompra.aspx?IDFactura=" + b.Value.ToString() + "','popup','Width=700,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')"
        End If

    End Sub

    Protected Sub LnkMasInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LnkMasInfo.Click
        If CboFacturas.Enabled Then
            Me.Response.Write("<script languaje='javascript'>var popup = window.open('FrmDetalleDeFacturaCompra.aspx?IDFactura=" + CboFacturas.SelectedValue.ToString() + "','popup','Width=700,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')</script>")
            LblError.Text = ""
        Else
            LblError.Text = "Error, no se puede mostrar una factura inexistente."
        End If
    End Sub

    Protected Sub LinkCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkCancelar.Click
        Dim Cont As Integer
        Cont = 0
        For Cont = 0 To CboFacturas.Items.Count - 1
            CboFacturas.Items(Cont).Enabled = True
        Next
        LimpiarCampos()
        LlenarGrid(-1)
    End Sub

    Protected Sub LinkGuardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkGuardar.Click
        Dim Contador As Integer = 0
        Dim i As Integer
        Dim DtsImputaciones As DataSet = Session("DtsImputaciones")
        If Not (DtsImputaciones.Tables(0).Rows.Count > 0) Then
            Contador = Contador + 1
            LblError.Text = "Error, No ha cargado las imputaciones."
        End If

        LlenarGrid(-1)
        If (GridFacturas.DataSource.tables(0).rows.count > 0) And Contador = 0 Then
            Dim IdOrden As String
            Try
                IdOrden = OrdenDePago.Insertar(LblTotal.Text, CboProveedor.SelectedValue.ToString(), TxtObservacion.Text).Tables(0).Rows(0)("CodigoOrdenDePago").ToString()
                For i = 0 To DtsImputaciones.Tables(0).Rows.Count - 1
                    If DtsImputaciones.Tables(0).Rows(i)("Banco").ToString() <> "" And _
                    DtsImputaciones.Tables(0).Rows(i)("Cuenta").ToString() <> "" And _
                    DtsImputaciones.Tables(0).Rows(i)("Chequera").ToString() <> "" And _
                    DtsImputaciones.Tables(0).Rows(i)("Cheque").ToString() <> "" Then 'cheque propio
                        ChequesPropios.InsertarChequePropio(DtsImputaciones.Tables(0).Rows(i)("Cheque").ToString(), _
                                  DtsImputaciones.Tables(0).Rows(i)("Chequera").ToString(), _
                                  CboProveedor.SelectedValue.ToString(), DtsImputaciones.Tables(0).Rows(i)("Total").ToString(), LblFecha.Text, "", CboProveedor.SelectedItem.Text, CboProveedor.SelectedItem.Text, "")
                        OpCheque.Insertar(DtsImputaciones.Tables(0).Rows(i)("Cheque").ToString(), IdOrden, DtsImputaciones.Tables(0).Rows(i)("Total").ToString(), LblFecha.Text)
                    End If
                    If DtsImputaciones.Tables(0).Rows(i)("Banco").ToString() <> "" And _
                    DtsImputaciones.Tables(0).Rows(i)("Cuenta").ToString() <> "" And _
                    DtsImputaciones.Tables(0).Rows(i)("Cheque").ToString() = "" Then 'cuentas
                        OpCuenta.Insertar(DtsImputaciones.Tables(0).Rows(i)("Cuenta").ToString(), IdOrden, DtsImputaciones.Tables(0).Rows(i)("Total").ToString(), LblFecha.Text)
                    End If
                    If DtsImputaciones.Tables(0).Rows(i)("Nombre").ToString() <> "" And _
                    DtsImputaciones.Tables(0).Rows(i)("Banco").ToString() = "" And _
                    DtsImputaciones.Tables(0).Rows(i)("Cuenta").ToString() = "" And _
                     DtsImputaciones.Tables(0).Rows(i)("Idcheque").ToString() = "" And _
                    DtsImputaciones.Tables(0).Rows(i)("Total").ToString() <> "" Then  'otras
                        OpOtras.Insertar("2", IdOrden, DtsImputaciones.Tables(0).Rows(i)("Total").ToString(), LblFecha.Text)
                    End If
                    If DtsImputaciones.Tables(0).Rows(0)("IdCheque").ToString() <> "" Then
                        ChequeTercero.ModificarCheque(DtsImputaciones.Tables(0).Rows(0)("IdCheque").ToString(), "", "", "", "", "", "", "", "Endosado")

                    End If

                Next

            Catch ex As Exception
                IdOrden = ""
                LblError.Text = "Error, la Orden no se pudo grabar."
            End Try
            If IdOrden <> "" Then
                Dim Cont As Integer
                Cont = 0
                Dim VarError As Boolean
                VarError = False
                While Cont <= GridFacturas.DataSource.tables(0).rows.count - 1 And Not VarError
                    VarError = Not DetalleOrdenDePago.Insertar(GridFacturas.DataSource.tables(0).rows(Cont)("Numero").ToString(), GridFacturas.DataSource.tables(0).rows(Cont)("Total").ToString(), IdOrden)
                    Cont = Cont + 1
                End While

                If Not VarError Then
                    Cont = 0
                    While Cont <= GridFacturas.DataSource.tables(0).rows.count - 1 And Not VarError
                        VarError = Not Factura.Modificar(GridFacturas.DataSource.tables(0).rows(Cont)("CodigoFactura").ToString(), "", "", "CANCELADA", "", "", "", "")
                        Cont = Cont + 1
                    End While
                End If
                If Not VarError Then
                    BtnImprimir.Visible = True
                    Session("RptOrdendePago") = OrdenDePago.ImprimirOrden(IdOrden)

                End If
                If VarError Then
                    DetalleOrdenDePago.Eliminar("", IdOrden)
                    OrdenDePago.Eliminar(IdOrden)
                    Cont = 0
                    While Cont <= GridFacturas.DataSource.tables(0).rows.count - 1
                        Factura.Modificar(GridFacturas.DataSource.tables(0).rows(Cont)("CodigoFactura").ToString(), "", "", "PENDIENTE", "", "", "", "")
                        Cont = Cont + 1
                    End While
                    LblError.Text = "Error, la Orden no se pudo grabar."
                Else
                    LinkCancelar_Click(sender, e)
                    LLenarCboFacturas()
                End If
            End If

        Else
            If Contador = 0 Then
                LblError.Text = "Error, No existen facturas cargadas."
            Else
                LblError.Visible = True
            End If

        End If

    End Sub

    Protected Sub LinkNuevo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkNuevo.Click
        LinkCancelar_Click(sender, e)
    End Sub
End Class